package com.my.activity;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.*;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.*;
import com.amap.api.maps.model.*;
import com.my.R;
import com.my.util.ApiUtil;

public class SignInActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {

    private static final int WRITE_COARSE_LOCATION_REQUEST_CODE = 0;

    MapView mapView;
    TextView tvCity;
    TextView btnCheckIn;

    private AMap aMap;
    private Circle circle;
    private LatLng locLatLng = null;
    private LatLng comLatLng = null;
    private float radius = 200;

    //定位需要的声明
    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;
    private LocationSource.OnLocationChangedListener mListener = null;

    SharedPreferences preferences = null;
    JSONObject setting = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        preferences = this.getSharedPreferences("LOGIN_DATA", Context.MODE_PRIVATE);
        JSONObject user = JSONUtil.parseObj(preferences.getString("user", null));
        setting = JSONUtil.parseObj(preferences.getString("setting", null));
        radius = setting.getInt("range");
        mapView = findViewById(R.id.map);
        tvCity = findViewById(R.id.tv_city);
        btnCheckIn = findViewById(R.id.btn_check_in);
        mapView.onCreate(savedInstanceState);
        initView();
        Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                JSONObject rest = ((JSONObject) msg.obj);
                Toast.makeText(SignInActivity.this, rest.getStr("msg"), Toast.LENGTH_LONG).show();
            }
        };
        btnCheckIn.setOnClickListener(v -> {
            if(locLatLng != null && comLatLng != null) {
                float distance = AMapUtils.calculateLineDistance(locLatLng, comLatLng);
                if(distance <= radius) {
                    new Thread(() -> {
                        Message message = new Message();
                        String body = HttpRequest.post(ApiUtil.HTTP_ADDRESS + "nightSpot/add?userId=" + user.getLong("id")).execute().body();
                        message.obj = new JSONObject(body);
                        handler.sendMessage(message);
                    }).start();
                }else {
                    Toast.makeText(this, "当前位置不在打卡范围内，打卡失败！", Toast.LENGTH_LONG).show();
                }
            }else {
                Toast.makeText(this, "位置初始化异常，打卡失败！", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void initView() {
        aMap = mapView.getMap();
        UiSettings settings = aMap.getUiSettings();
        aMap.setLocationSource(this);
        settings.setMyLocationButtonEnabled(true);
        settings.setCompassEnabled(true);
        aMap.setMyLocationEnabled(true);
        if(Build.VERSION.SDK_INT >= 23) {
            showPermissions();
        }else {
            initLoc();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    public void showPermissions() {
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE
            }, WRITE_COARSE_LOCATION_REQUEST_CODE);
        } else {
            initLoc();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case WRITE_COARSE_LOCATION_REQUEST_CODE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initLoc();
                }else {
                    Toast.makeText(this, "获取位置权限失败，请手动开启", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(aMapLocation != null) {
            if(aMapLocation.getErrorCode() == 0) {
                aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                mListener.onLocationChanged(aMapLocation);
                aMap.addMarker(getMarkerOptions(aMapLocation));
                tvCity.setText(aMapLocation.getCity());
                Toast.makeText(getApplicationContext(), aMapLocation.getAddress(), Toast.LENGTH_LONG).show();
                locLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            }
        }
    }

    @Override
    public void activate(LocationSource.OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    private void initLoc() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(false);
        mLocationOption.setWifiActiveScan(true);
        mLocationOption.setMockEnable(false);
        mLocationOption.setInterval(3000);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    public MarkerOptions getMarkerOptions(AMapLocation location) {
        MarkerOptions options = new MarkerOptions();
        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_company));
        comLatLng = new LatLng(setting.getDouble("latitude"), setting.getDouble("longitude"));
        options.position(comLatLng);
        drawCircle(comLatLng);
        options.snippet("地址：" + location.getProvider() + location.getCity() + location.getDistrict() + location.getStreet());
        options.period(60);
        return options;
    }

    public void drawCircle(LatLng latLng) {
        if(circle != null) {
            circle = null;
        }
        circle = aMap.addCircle(new CircleOptions().center(latLng).radius(radius).fillColor(R.color.transparent1)
                .strokeColor(R.color.transparent1).strokeWidth(5));
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == 16908332) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

}